import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login.vue'
import home from '../components/home.vue'



Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' }, // 默认重定向到登入页面.
    { path: '/login', component: login },
    { path: '/home', component: home }
  ]
})
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 表示将要访问的路径
  //from 由哪个路径跳转而来
  //next 表示 【允许放行】的函数

  //当访问的是登入页面，不需要访问权限，直接放行.
  if (to.path === '/login') return next();
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next();

})

export default router
